package api

import (
	. "com.mgface.disobj/common"
	"encoding/json"
	"os"
	"sort"
	"strings"
)

//定位数据分片
//
//nodeAddr 节点的数组数据
//
//objRealName 对象数据文件名称
//
//filesize 文件大小
func Locate(object string) (nodeAddr []string, objRealName []string, filesize int64) {
	client := NewReconTCPClient(mnAddr)
	cmd := &Cmd{Name: "get", Key: "metadata", Value: object}
	cmd.Run(client)
	var results []Datadigest
	json.Unmarshal([]byte(cmd.Value), &results)
	var max int64 = 0
	var maxDatadigest Datadigest
	for _, data := range results {
		if data.Version > max {
			max = data.Version
			maxDatadigest = data
		}
	}
	//获取文件的CRC
	cmd = &Cmd{Name: "get", Key: "filecrc", Value: maxDatadigest.Hash}
	cmd.Run(client)

	var sd SharedDataslice
	json.Unmarshal([]byte(cmd.Value), &sd)
	//对数据切片进行排序
	sort.Stable(sd)
	nodeAddrs := make([]string, 0)
	objRealNames := make([]string, 0)
	//遍历文件CRC，获取请求数据的数据节点，实际文件名，分片大小
	for _, data := range sd {
		url := strings.Split(data.SharedFileUrlLocate, string(os.PathSeparator))
		nodeAddrs = append(nodeAddrs, url[0])
		objRealNames = append(objRealNames, url[len(url)-1])
	}

	return nodeAddrs, objRealNames, maxDatadigest.Datasize
}

type SharedDataslice []SharedData

//数据分片切片长度
func (s SharedDataslice) Len() int {
	return len(s)
}

//数据分片的数据交换
func (s SharedDataslice) Swap(i, j int) {
	s[i], s[j] = s[j], s[i]
}

//数据分片的比较
func (s SharedDataslice) Less(i, j int) bool {
	return s[i].SharedIndex < s[j].SharedIndex
}
